package gnetty

import (
	"gitee.com/llakcs/gnetty/commom"
	"gitee.com/llakcs/gnetty/config"
	"log"
	"unsafe"
)

//func main() {
//	//serverDemo()
//	clientDemo()
//}

//服务器示例
func serverDemo() {
	//创建配置方法1
	o := config.ServerConfigBuild()
	o.WithPort("10010")                //设置端口
	o.WithChanSize(1000)               //设置队列大小
	o.WithBufferSize(1024)             //设置接收缓冲区大小
	o.WithEnale(true)                  //是否启用
	o.WithChanReadHandler(channelread) //设置业务处理器
	o.WithDecodeHandler(decode)        //设置解码处理器
	o.WithEncodeHandler(encode)        //设置编码处理器
	//创建配置方法2
	o1 := &config.ServerConfig{
		Port:            "10086",
		ReadTimeout:     0,
		BufferSize:      1024,
		ChanSize:        1000,
		Enable:          true,
		ChanReadHandler: channelread1,
		DecoderHandler:  decode1,
		EncodeHandler:   encode1,
	}
	//创建tcp服务器,设置主线程和工作线程绑定配置
	s := NewTcpServer(30, 30, o, o1)
	//开始监听
	s.ListenTcp()
}

//客户端示例
func clientDemo() {
	conf := config.ClientConfBuild()
	conf.WithBufferSize(1024)
	conf.WithChanSize(1024)
	conf.WithChanReadHandler(channelread)
	conf.WithDecodeHandler(decode)
	conf.WithEncodeHandler(encode)
	conf.WithIpAddr("127.0.0.1:8877")
	c := NewConn(conf)
	c.Connect()
	select {}
}

func channelread1(c *commom.ChannelProcess) {
	log.Println("channel1---read:", c.DecodeData.(string))
	//推送到编码通道
	c.WriteAndFlush(c.DecodeData)
}

func decode1(ctx *commom.ChannelContext) {
	log.Println("decode1---read:")
	//添加业务处理通道
	ctx.Add(string(ctx.Buf))
}

func encode1(e *commom.EncodeCtx) {
	log.Println("encode1---read:")
	a := []byte("hello world1")
	//发送
	e.WriteBytes(a)
}

func channelread(c *commom.ChannelProcess) {
	//字符串类型 c.DecodeData.(string)
	//结构体 interface转结构体
	log.Println("channel---read:", c.DecodeData)
	c.WriteAndFlush(c.DecodeData)
}

func decode(ctx *commom.ChannelContext) {
	log.Println("decode---read:")
	//字符串类型
	ctx.Add(ctx.Buf)
}

func encode(e *commom.EncodeCtx) {
	//log.Println("encode---read:")
	a := []byte("hello world---------every one")
	//结构体发送
	//data := e.Data.(int)

	e.WriteBytes(a)
}

func StringToBytes(data string) []byte {
	return *(*[]byte)(unsafe.Pointer(&data))
}

type test struct {
	Name string
	Age  string
}
